package edu.cmu.ibill.model;

import edu.cmu.ibill.databeans.User;

import org.mybeans.dao.*;
import org.mybeans.factory.*;

public class UserDAO {

	private BeanFactory<User> factory;

	public UserDAO(String driver, String URL, String user, String pw)
			throws DAOException {
		try {
			// Get a BeanTable to create the "photo" table

			BeanTable.useJDBC(driver, URL, user, pw);

			BeanTable<User> userTable = BeanTable.getInstance(User.class,
					"ibill_user");

			if (!userTable.exists()) {
				userTable.create("id");
			}

			userTable.setIdleConnectionCleanup(true);

			// Get a BeanFactory which the actions will use to read and write
			// rows of the "likeable" table
			factory = userTable.getFactory();
		} catch (BeanFactoryException e) {
			throw new DAOException(e);
		}
	}

	public User Lookup(String email) {
		User user = null;

		try {
			User[] list = factory.match(MatchArg.equals("emailAddress", email));
			if (list.length > 0)
				user = list[0];
		} catch (RollbackException e) {
			return null;
		}

		return user;
	}

	public String getUserEmail(int id) {
		String email = "";

		try {
			User[] list = factory.match(MatchArg.equals("id", id));
			if (list.length > 0)
				email = list[0].getEmailAddress();
		} catch (RollbackException e) {
			return "";
		}

		return email;
	}

	public void create(User user) throws DAOException {
		if (Lookup(user.getEmailAddress()) == null) {
			try {
				Transaction.begin();

				User dbUser = factory.create();
				factory.copyInto(user, dbUser);

				Transaction.commit();
			} catch (RollbackException e) {
				throw new DAOException(e);
			} finally {
				if (Transaction.isActive())
					Transaction.rollback();
			}
		} else {
			throw new DAOException("Email already exists");
		}
	}

	public String getNamebyUserID(int id) {
		String name = "";

		try {
			User[] list = factory.match(MatchArg.equals("id", id));
			if (list.length > 0)
				name = list[0].getUserName();
		} catch (RollbackException e) {
			return "";
		}

		return name;

	}

	public void update(User user) throws DAOException {
		try {
			Transaction.begin();

			User dbUser = factory.lookup(user.getId());
			
			if(dbUser == null)
				throw new DAOException("User doesn't exist!");
			
			factory.copyInto(user, dbUser);

			Transaction.commit();
		} catch (RollbackException e) {
			throw new DAOException(e);
		} finally {
			if (Transaction.isActive())
				Transaction.rollback();
		}
	}
}
